
///
///  create by zmtzawqlp on 2019/11/20
///
import 'dart:math';

import 'package:extended_image/extended_image.dart';
import 'package:fancy_shimmer_image/fancy_shimmer_image.dart';
import 'package:ff_annotation_route_library/ff_annotation_route_library.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:get/get_core/src/get_main.dart';
import 'package:loading_more_list/loading_more_list.dart';
import 'package:pull_to_refresh_notification/pull_to_refresh_notification.dart';
import 'package:qianyi/state/token.dart';
import 'package:waterfall_flow/waterfall_flow.dart';

import '../../../../controller/imageDetailVideoController.dart';
import '../../../../entity/home/recommend/Record.dart';
import '../../../../network/http_config.dart';
import '../../../../network/http_manager.dart';
import '../../../../pages/home/mine/dongtai/PageViewMine.dart';
import '../../../../utils/throttle.dart';
import '../../common/data/tu_chong_repository.dart';
import '../../common/data/tu_chong_source.dart';
import '../../common/widget/item_builder.dart';
import '../../common/widget/push_to_refresh_header.dart';

@FFRoute(
  name: 'fluttercandies://known-sized',
  routeName: 'known-sized',
  description: 'show how to build a known-sized item with waterfall flow list.',
  exts: <String, dynamic>{
    'group': 'Complex',
    'order': 1,
  },
)

class KnownSizedDemo1 extends StatefulWidget {
  @override
  _KnownSizedDemoState1 createState() => _KnownSizedDemoState1();
}

class _KnownSizedDemoState1 extends State<KnownSizedDemo1> {
  RecommendRepository listSourceRepository = RecommendRepository();
  TokenController tokenController = Get.find();
  ImageDetailVideoController imageDetailVideoController = Get.find<ImageDetailVideoController>();
  DateTime? dateTimeNow;
  @override
  void dispose() {
    super.dispose();
    listSourceRepository.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return PullToRefreshNotification(
      pullBackOnRefresh: false,
      maxDragOffset: maxDragOffset,
      armedDragUpCancel: false,
      onRefresh: onRefresh,
      child: LoadingMoreCustomScrollView(
        slivers: <Widget>[
          SliverToBoxAdapter(
            child: PullToRefreshContainer(
                    (PullToRefreshScrollNotificationInfo? info) {
                  return PullToRefreshHeader(info, dateTimeNow);
                }),
          ),
          LoadingMoreSliverList<Record>(
            SliverListConfig<Record>(
              extendedListDelegate:
              const SliverWaterfallFlowDelegateWithMaxCrossAxisExtent(
                maxCrossAxisExtent: 300,
                crossAxisSpacing: 0,
                mainAxisSpacing: 1,
              ),
              itemBuilder: buildWaterfallFlowItem1,
              sourceList: listSourceRepository,
              padding: const EdgeInsets.all(1.0),
              lastChildLayoutType: LastChildLayoutType.foot,
            ),
          )
        ],
      ),
    );
  }
  Map<int, double> imagesHeightMap = {};

  double getRandomHeight1(int index) {
    // 检查imagesHeightMap中是否已经存在对应索引的高度
    if (imagesHeightMap.containsKey(index)) {
      // 如果存在，返回该高度
      return imagesHeightMap[index]!;
    } else {
      // 如果不存在，生成一个新的随机高度并添加到Map中
      double height = Random().nextDouble() * (200 - 80) + 168;
      imagesHeightMap[index] = height;
      return height;
    }
  }
  Widget buildWaterfallFlowItem1(BuildContext c, Record item, int index,
      {bool konwSized = true}) {
    const double fontSize = 12.0;

    Record trendEntity = item;

    return GestureDetector(
      onTap: () async {
        HudUtil.showBeautiful(context);
        Map<String,dynamic> params = {
          "uid":tokenController.uid,
          "mid":trendEntity.id!
        };
        HttpManager.getInstance().request(url: "/platform/browseRecord/addBrowseRecord",params: params,method: Method.post);

        imageDetailVideoController.imageDetailId.value = trendEntity.id!;
        await imageDetailVideoController.getImageVideoDetail();
        // Loader.hide();

        HudUtil.dismiss();
        Get.toNamed("/ui/home/imageVideoDetail");

      },
      child: Card(
        margin: EdgeInsets.all(1.5),
        child: ClipRRect(
          borderRadius: BorderRadius.circular(4.0),
          child:  Column(
            children: [
              FancyShimmerImage(

                height: getRandomHeight1(index),
                imageUrl: trendEntity.cover!,
              )
              ,


              Align(
                alignment: Alignment.centerLeft,
                child: Text(
                  trendEntity.content as String,maxLines: 2,softWrap: true, // 允许文本在超出最大行数时以省略号结束
                  overflow: TextOverflow.ellipsis, style: TextStyle(fontWeight: FontWeight.w400),// 设置文本左对齐
                ),

              )
              ,
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Row(
                    children: [
                      ClipOval(
                          child: FancyShimmerImage(imageUrl: trendEntity.avatar as String,width: 20,height: 20,)
                      ),

                      Text(trendEntity.username as String),
                    ],
                  ),

                  Row(
                    children: [
                      Icon(
                        CupertinoIcons.heart,size: 14,),
                      Text(trendEntity.agreeCount as String)

                    ],
                  )
                ],
              )
            ],
          ),
        ),
      ),
    );
  }
  Future<bool> onRefresh() {
    return listSourceRepository.refresh().whenComplete(() {
      dateTimeNow = DateTime.now();
    });
  }
}



class KnownSizedDemo extends StatefulWidget {
  @override
  _KnownSizedDemoState createState() => _KnownSizedDemoState();
}

class _KnownSizedDemoState extends State<KnownSizedDemo> {
  TuChongRepository listSourceRepository = TuChongRepository();
  DateTime? dateTimeNow;
  @override
  void dispose() {
    super.dispose();
    listSourceRepository.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return PullToRefreshNotification(
      pullBackOnRefresh: false,
      maxDragOffset: maxDragOffset,
      armedDragUpCancel: false,
      onRefresh: onRefresh,
      child: LoadingMoreCustomScrollView(
        slivers: <Widget>[
          SliverToBoxAdapter(
            child: PullToRefreshContainer(
                (PullToRefreshScrollNotificationInfo? info) {
              return PullToRefreshHeader(info, dateTimeNow);
            }),
          ),
          LoadingMoreSliverList<TuChongItem>(
            SliverListConfig<TuChongItem>(
              extendedListDelegate:
                  const SliverWaterfallFlowDelegateWithMaxCrossAxisExtent(
                maxCrossAxisExtent: 300,
                crossAxisSpacing: 5,
                mainAxisSpacing: 5,
              ),
              itemBuilder: buildWaterfallFlowItem,
              sourceList: listSourceRepository,
              padding: const EdgeInsets.all(5.0),
              lastChildLayoutType: LastChildLayoutType.foot,
            ),
          )
        ],
      ),
    );
  }

  Future<bool> onRefresh() {
    return listSourceRepository.refresh().whenComplete(() {
      dateTimeNow = DateTime.now();
    });
  }
}
